package com.example.fasteranim;

import android.graphics.drawable.AnimationDrawable;
import android.os.Bundle;
import android.view.View;
import android.widget.ImageView;

import androidx.appcompat.app.AppCompatActivity;

public class MainActivity extends AppCompatActivity {
    private ImageView imageView;
    private FasterAnimationsContainer mFasterAnim;
    private AnimationDrawable drawableAnim;

    private static final int[] ANIM_RES_ID = {R.drawable.anim_01, R.drawable.anim_02, R.drawable.anim_03,
            R.drawable.anim_04, R.drawable.anim_05, R.drawable.anim_06, R.drawable.anim_07,
            R.drawable.anim_08, R.drawable.anim_09, R.drawable.anim_10, R.drawable.anim_11,
            R.drawable.anim_12, R.drawable.anim_13, R.drawable.anim_14, R.drawable.anim_15,
            R.drawable.anim_16};

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        imageView = findViewById(R.id.imageView);


        mFasterAnim = new FasterAnimationsContainer(imageView);

        findViewById(R.id.bt_drawable_anim).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startAnimationDrawable();
            }
        });

        findViewById(R.id.bt_fast_anim).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startFastAnim();
            }
        });
    }

    @Override
    protected void onResume() {
         super.onResume();
    }

    @Override
    protected void onPause() {
        super.onPause();
        if(drawableAnim!=null){
            drawableAnim.stop();
        }

        if(mFasterAnim!=null){
            mFasterAnim.stop();
        }

    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
    }

    private void startAnimationDrawable() {
        imageView.setImageResource(R.drawable.anim);
        drawableAnim = (AnimationDrawable) imageView.getDrawable();
        drawableAnim.stop();
        drawableAnim.start();
    }

    private void startFastAnim() {

        mFasterAnim.removeAllFrames();
        mFasterAnim.addAllFrames(ANIM_RES_ID, 100);
        mFasterAnim.setOnAnimationFrameChangedListener(
                new FasterAnimationsContainer.OnAnimationFrameChangedListener() {
                    @Override
                    public void onAnimationFrameChanged(int index) {
                        if (index == ANIM_RES_ID.length - 1) {
                            mFasterAnim.stop();
                        }
                    }
                });
        mFasterAnim.stop();
        mFasterAnim.start();
    }
}